﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Whir.Common.WebHelper;
using Whir.Publish;

public partial class UserControls_ContentControl_NewCommonContentManage : System.Web.UI.UserControl, IContentUserControl
{
    /// <summary>
    /// 获取当前功能模块对应的表的名称
    /// </summary>
    protected string tableName = "";

    /// <summary>
    /// 获取当前功能模块对应表的主键名称
    /// </summary>
    protected string primaryKeyName = "";

    /// <summary>
    /// 跳转页面的标题
    /// </summary>
    protected string PopWindowTitle = "";
    /// <summary>
    /// 添加按钮跳转的Url
    /// </summary>
    protected string AddUrl = "";

    #region 事件
    public delegate void RowCommand(object sender, GridViewCommandEventArgs e);
    public event RowCommand CommonContentManage_RowCommand;
    #endregion

    public GridView GridView
    {
        get { return this.GridView1; }
    }

    public Whir.Controls.UI.WebControls.ezGridView ezGridView
    {
        get
        {
            return GridView1;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Whir.Model.Whir_Model model = new Whir.Model.Whir_Model();
        Whir.BLL.Whir_Model bll = new Whir.BLL.Whir_Model();
        model = bll.GetModel(ModelID);
        tableName = model.tableName;
        primaryKeyName = ContentManage.GetCustomTablePrimaryKeyName(model.tableName);
        AddUrl = "Content.aspx?Action=Add&ModelID=" + ModelID + "&ModelFormID=" + ModelFormID + "&TypeID=" + TypeID + "&url=" + Server.UrlEncode(NetRequest.GetUrl());

        if (!IsPostBack)
        {
            //初始化控件显示属性
            InitPageControl();

            //绑定数据
            BindData();
        }
    }

    #region 初始化控件显示属性
    private void InitPageControl()
    {

        //是否为单页
        Whir.BLL.Whir_Column bll = new Whir.BLL.Whir_Column();
        Whir.Model.Whir_Column model = new Whir.Model.Whir_Column();
        model = bll.GetModel(TypeID);

        PopWindowTitle = model.columnName;

        string sql = string.Format("SELECT {0} FROM {1} WHERE {2} = {3}", primaryKeyName, tableName, "TypeID", TypeID);
        object item = Whir.SQLServerDAL.DbHelperSQL.GetSingle(sql);
        if (item != null)
        {
            int itemId = int.Parse(item.ToString());

            if (itemId != 0)
            {
                //是否为单页，如果是单页则直接跳转到内容编辑页面
                if (model.IsSinglePage)
                {
                    //btnSubmit.Visible = false;
                    btnDelete.Visible = false;

                    Response.Redirect(string.Format("Content.aspx?ModelFormID={0}&ModelID={1}&Action=Modify&ItemID={2}&TypeID={3}", ModelFormID, ModelID, itemId, TypeID));
                }
            }
        }
    }
    #endregion

    #region 绑定数据
    public void BindData()
    {
        //Whir.BLL.Whir_ModelForm modelFormModel = new Whir.BLL.Whir_ModelForm();

        ////字段标题数组
        //string fieldTitles = "";
        ////字段 ID 数组
        //string fieldIDs = modelFormModel.GetFieldIDs(ModelFormID);
        ////字段列数组
        //string fieldNames = "";

        //Whir.BLL.Whir_Field fieldBll = new Whir.BLL.Whir_Field();

        ////获取标题列表
        //DataTable dtTitles = fieldBll.GetList("FieldID in (" + fieldIDs + ") AND ModelID = " + ModelID).Tables[0];

        ////获取字段列表
        //DataTable dtContents = Whir.SQLServerDAL.DbHelperSQL.GetDataTable(" FieldName ", "Whir_Field", " FieldID in (" + fieldIDs + ")", "Sort");

        ////获取列标题
        //foreach (DataRow dr in dtTitles.Rows)
        //{
        //    fieldTitles += dr["alias"].ToString() + ",";
        //}
        //fieldTitles = fieldTitles.TrimEnd(',');

        ////获取表字段
        //foreach (DataRow dr in dtContents.Rows)
        //{
        //    fieldNames += dr["FieldName"].ToString().ToLower() + ",";
        //}
        //fieldNames = fieldNames.TrimEnd(',');

        ////绑定值
        //DataSet ds = Whir.SQLServerDAL.DbHelperSQL.GetList(tableName,
        //    primaryKeyName,
        //    primaryKeyName + "," + fieldNames,
        //    AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex - 1,
        //    Where, "", "CreateDate desc");

        ////获取数据集总数
        //int rowCount = int.Parse(ds.Tables[1].Rows[0][0].ToString());
        //AspNetPager1.RecordCount = rowCount;

        //this.GridView1.Columns.Clear();
        //this.GridView1.AutoGenerateColumns = false;
        //this.GridView1.DataKeyNames = new string[] { primaryKeyName };

        //#region 创建列数据
        ////创建编号列
        //BoundField IdField = new BoundField();
        //IdField.HeaderText = "编号";
        //IdField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        //IdField.DataField = primaryKeyName;
        //this.GridView1.Columns.Add(IdField);

        ////创建表单数据
        //BoundField ItemField;
        //for (int i = 0; i < fieldNames.Split(',').Length; i++)
        //{
        //    ItemField = new BoundField();
        //    ItemField.HeaderText = fieldTitles.Split(',')[i].ToString();
        //    ItemField.DataField = fieldNames.Split(',')[i].ToString();
        //    ItemField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        //    this.GridView1.Columns.Add(ItemField);
        //}
        //#endregion

        //#region 管理操作

        ////是否显示默认的按钮（“审核”，“推荐”，“编辑”，“删除”）
        //bool flag = true;

        //#region 动态管理操作解析
        //if (!string.IsNullOrEmpty(Settings))
        //{
        //    string[] str = Settings.Split('|');

        //    for (int i = 0; i < str.Length; i++)
        //    {
        //        //是否显示默认的按钮
        //        if (str[i].Split(',')[1].ToString().ToLower() == "show")
        //            flag = true;
        //        else
        //            flag = false;

        //        if (str[i].Split(',')[0].ToString() == "1")
        //        {
        //            ButtonField temp = new ButtonField();
        //            temp.ButtonType = ButtonType.Link;
        //            temp.HeaderText = str[i].Split(',')[2].ToString();
        //            temp.Text = str[i].Split(',')[3].ToString();
        //            temp.CommandName = str[i].Split(',')[4].ToString();
        //            temp.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        //            GridView1.Columns.Add(temp);
        //        }
        //        else if (Settings.Split(',')[0].ToString() == "2")
        //        {
        //            HyperLinkField temp = new HyperLinkField();
        //            temp.HeaderText = str[i].Split(',')[2].ToString();
        //            temp.Text = str[i].Split(',')[3].ToString();
        //            temp.NavigateUrl = str[i].Split(',')[4].ToString();
        //            GridView1.Columns.Add(temp);
        //        }
        //    }

        //}
        //#endregion

        //if (flag)
        //{
        //    #region 审核
        //    if (fieldNames.Contains("ischeck"))
        //    {
        //        ButtonField checkButton = new ButtonField();
        //        checkButton.CommandName = "CheckItem";
        //        //checkButton.ButtonType = ButtonType.Image;
        //        //checkButton.ImageUrl = "~/Whir_System/image/CommonImage/eip_checkver.gif";
        //        checkButton.ButtonType = ButtonType.Link;
        //        checkButton.Text = "审核";
        //        checkButton.HeaderText = "审核";
        //        checkButton.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        //        this.GridView1.Columns.Add(checkButton);
        //    }
        //    #endregion

        //    #region 推荐
        //    if (fieldNames.Contains("istop"))
        //    {
        //        ButtonField topButton = new ButtonField();
        //        topButton.CommandName = "TopItem";
        //        //topButton.ButtonType = ButtonType.Image;
        //        //topButton.ImageUrl = "~/Whir_System/image/CommonImage/eip_agree.gif";
        //        topButton.ButtonType = ButtonType.Link;
        //        topButton.Text = "推荐";
        //        topButton.HeaderText = "推荐";
        //        topButton.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        //        this.GridView1.Columns.Add(topButton);
        //    }
        //    #endregion

        //    #region 编辑
        //    ButtonField editButton = new ButtonField();
        //    editButton.CommandName = "ModifyItem";
        //    editButton.ButtonType = ButtonType.Image;
        //    editButton.ImageUrl = "~/Whir_System/image/CommonImage/eip_edit.gif";
        //    editButton.HeaderText = "编辑";
        //    editButton.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        //    this.GridView1.Columns.Add(editButton);
        //    #endregion

        //    #region 删除
        //    ButtonField deleteButton = new ButtonField();
        //    deleteButton.ButtonType = ButtonType.Image;
        //    deleteButton.ImageUrl = "~/Whir_System/image/CommonImage/eip_deleted.gif";
        //    deleteButton.CommandName = "DeleteItem";
        //    deleteButton.HeaderText = "删除";
        //    deleteButton.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        //    this.GridView1.Columns.Add(deleteButton);
        //    #endregion
        //}
        //#endregion

        //#region 查看
        ///*ButtonField PreviewButton = new ButtonField();
        //PreviewButton.ButtonType = ButtonType.Link;
        //PreviewButton.CommandName = "PreviewItem";
        //PreviewButton.HeaderText = "查看";
        //PreviewButton.Text = "查看";
        //PreviewButton.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        //this.GridView1.Columns.Add(PreviewButton);*/
        //#endregion

        //if (rowCount > 0)
        //{
        //    DataView dv = ds.Tables[0].DefaultView;
        //    dv.Sort = "CreateDate desc";
        //    GridView1.DataSource = dv;
        //    GridView1.DataBind();
        //    divMessage.Visible = false;
        //}
        //else
        //{
        //    GridView1.Controls.Clear();
        //    divMessage.Visible = true;
        //}

        //Whir.BLL.Whir_ModelForm modelFormModel = new Whir.BLL.Whir_ModelForm();

        ////字段标题数组
        //string fieldTitles = "";
        ////字段 ID 数组
        //string fieldIDs = modelFormModel.GetFieldIDs(ModelFormID);
        ////字段列数组
        //string fieldNames = "";

        //Whir.BLL.Whir_Field fieldBll = new Whir.BLL.Whir_Field();

        ////获取标题列表
        //DataTable dtTitles = fieldBll.GetList("FieldID in (" + fieldIDs + ") AND ModelID = " + ModelID).Tables[0];

        ////获取字段列表
        //DataTable dtContents = Whir.SQLServerDAL.DbHelperSQL.GetDataTable(" FieldName ", "Whir_Field", " FieldID in (" + fieldIDs + ")", "Sort");

        ////获取列标题
        //foreach (DataRow dr in dtTitles.Rows)
        //{
        //    fieldTitles += dr["alias"].ToString() + ",";
        //}
        //fieldTitles = fieldTitles.TrimEnd(',');

        ////获取表字段
        //foreach (DataRow dr in dtContents.Rows)
        //{
        //    fieldNames += dr["FieldName"].ToString().ToLower() + ",";
        //}
        //fieldNames = fieldNames.TrimEnd(',');

        string[] fieldstr = createBindSQL();

        //字段标题数组
        string fieldTitles = fieldstr[0];
        //字段 ID 数组
        string fieldIDs = fieldstr[1];
        //字段列数组
        string fieldNames = fieldstr[2];

        string oldfieldNames = fieldstr[3];


        //绑定值
        DataSet ds = Whir.SQLServerDAL.DbHelperSQL.GetList(tableName,
            primaryKeyName,
            primaryKeyName + "," + fieldNames,
            AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex - 1,
            Where, "", "CreateDate desc");

        //获取数据集总数
        int rowCount = int.Parse(ds.Tables[1].Rows[0][0].ToString());
        AspNetPager1.RecordCount = rowCount;

        this.GridView1.Columns.Clear();
        this.GridView1.AutoGenerateColumns = false;
        this.GridView1.DataKeyNames = new string[] { primaryKeyName };

        #region 创建列数据
        //创建编号列
        BoundField IdField = new BoundField();
        IdField.HeaderText = "编号";
        IdField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        IdField.DataField = primaryKeyName;
        this.GridView1.Columns.Add(IdField);

        //创建表单数据
        BoundField ItemField;
        Whir.BLL.Whir_Field fieldBll = new Whir.BLL.Whir_Field();
        Whir.Model.Whir_Field fieldModel = new Whir.Model.Whir_Field();

        for (int i = 0; i < fieldNames.Split(',').Length; i++)
        {
            fieldModel = fieldBll.GetModel(int.Parse(fieldIDs.Split(',')[i].ToString()));
            switch ((FieldType)fieldModel.fieldType)
            {
                case FieldType.PictureType:
                    string[] PictureTypeStr = { fieldNames.Split(',')[i].ToString() };
                    HyperLinkField PictureTypeLinkField = new HyperLinkField();
                    PictureTypeLinkField.HeaderText = fieldTitles.Split(',')[i].ToString();
                    //ItemField.
                    PictureTypeLinkField.Text = "预览";
                    PictureTypeLinkField.Target = "_blank";
                    PictureTypeLinkField.DataNavigateUrlFields = PictureTypeStr;
                    PictureTypeLinkField.DataNavigateUrlFormatString = Whir.Common.Settings.AppSettings["SystemPath"].ToString() + "UploadFiles/image/{0}";
                    PictureTypeLinkField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                    this.GridView1.Columns.Add(PictureTypeLinkField);
                    break;
                case FieldType.FileType:
                    string[] FileTypeStr = { fieldNames.Split(',')[i].ToString() };
                    HyperLinkField LinkField = new HyperLinkField();
                    LinkField.HeaderText = fieldTitles.Split(',')[i].ToString();
                    //ItemField.
                    LinkField.Text = "下载";
                    //LinkField.NavigateUrl = fieldNames.Split(',')[i].ToString();
                    LinkField.DataNavigateUrlFields = FileTypeStr;
                    LinkField.DataNavigateUrlFormatString = Whir.Common.Settings.AppSettings["SystemPath"].ToString() + "{0}";
                    LinkField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                    this.GridView1.Columns.Add(LinkField);
                    break;
                case FieldType.ListBoxType:
                case FieldType.DateTimeType:
                case FieldType.BoolType:
                case FieldType.ColorType:
                case FieldType.LinkType:
                case FieldType.MoneyType:
                case FieldType.MultipleTextType:
                case FieldType.MultipleHtmlTextType:
                case FieldType.NumberType:
                case FieldType.TextType:
                default:
                    ItemField = new BoundField();
                    ItemField.HeaderText = fieldTitles.Split(',')[i].ToString();
                    ItemField.DataField = oldfieldNames.Split(',')[i].ToString();
                    ItemField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                    this.GridView1.Columns.Add(ItemField);
                    break;
            }
        }
        #endregion

        #region 管理操作

        //是否显示默认的按钮（“审核”，“推荐”，“编辑”，“删除”）
        bool flag = true;

        #region 动态管理操作解析
        if (!string.IsNullOrEmpty(Settings))
        {
            string[] str = Settings.Split('|');

            for (int i = 0; i < str.Length; i++)
            {
                //是否显示默认的按钮
                if (str[i].Split(',')[1].ToString().ToLower() == "show")
                    flag = true;
                else
                    flag = false;

                if (str[i].Split(',')[0].ToString() == "1")
                {
                    ButtonField temp = new ButtonField();
                    temp.ButtonType = ButtonType.Link;
                    temp.HeaderText = str[i].Split(',')[2].ToString();
                    temp.Text = str[i].Split(',')[3].ToString();
                    temp.CommandName = str[i].Split(',')[4].ToString();
                    temp.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                    GridView1.Columns.Add(temp);
                }
                else if (Settings.Split(',')[0].ToString() == "2")
                {
                    HyperLinkField temp = new HyperLinkField();
                    temp.HeaderText = str[i].Split(',')[2].ToString();
                    temp.Text = str[i].Split(',')[3].ToString();
                    temp.NavigateUrl = str[i].Split(',')[4].ToString();
                    GridView1.Columns.Add(temp);
                }
            }

        }
        #endregion

        if (flag)
        {
            #region 审核
            if (fieldNames.Contains("ischeck"))
            {
                ButtonField checkButton = new ButtonField();
                checkButton.CommandName = "CheckItem";
                //checkButton.ButtonType = ButtonType.Image;
                //checkButton.ImageUrl = "~/Whir_System/image/CommonImage/eip_checkver.gif";
                checkButton.ButtonType = ButtonType.Link;
                checkButton.Text = "审核";
                checkButton.HeaderText = "审核";
                checkButton.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                this.GridView1.Columns.Add(checkButton);
            }
            #endregion

            #region 推荐
            if (fieldNames.Contains("istop"))
            {
                ButtonField topButton = new ButtonField();
                topButton.CommandName = "TopItem";
                //topButton.ButtonType = ButtonType.Image;
                //topButton.ImageUrl = "~/Whir_System/image/CommonImage/eip_agree.gif";
                topButton.ButtonType = ButtonType.Link;
                topButton.Text = "推荐";
                topButton.HeaderText = "推荐";
                topButton.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                this.GridView1.Columns.Add(topButton);
            }
            #endregion

            #region 编辑
            ButtonField editButton = new ButtonField();
            editButton.CommandName = "ModifyItem";
            editButton.ButtonType = ButtonType.Image;
            editButton.ImageUrl = "~/Whir_System/image/CommonImage/eip_edit.gif";
            editButton.HeaderText = "编辑";
            editButton.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            this.GridView1.Columns.Add(editButton);
            #endregion

            #region 删除
            //ButtonField deleteButton = new ButtonField();
            //deleteButton.ButtonType = ButtonType.Image;
            //deleteButton.ImageUrl = "~/Whir_System/image/CommonImage/eip_deleted.gif";
            //deleteButton.CommandName = "DeleteItem";
            //deleteButton.HeaderText = "删除";
            //deleteButton.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            //this.GridView1.Columns.Add(deleteButton);
            #endregion
        }
        #endregion

        #region 查看
        /*ButtonField PreviewButton = new ButtonField();
        PreviewButton.ButtonType = ButtonType.Link;
        PreviewButton.CommandName = "PreviewItem";
        PreviewButton.HeaderText = "查看";
        PreviewButton.Text = "查看";
        PreviewButton.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        this.GridView1.Columns.Add(PreviewButton);*/
        #endregion

        if (rowCount > 0)
        {
            DataView dv = ds.Tables[0].DefaultView;
            dv.Sort = "CreateDate desc";
            GridView1.DataSource = dv;
            GridView1.DataBind();

            this.GridView1.Columns[0].Visible = false;//隐藏编号列

            divMessage.Visible = false;
        }
        else
        {
            GridView1.Controls.Clear();
            divMessage.Visible = true;
        }
    }


    /// <summary>
    /// 创建SQL语句
    /// </summary>
    /// <returns></returns>
    private string[] createBindSQL()
    {
        string[] strReturn = { "fieldTitles", "fieldIDs", "fieldNames", "oldfieldNames" };

        Whir.BLL.Whir_ModelForm modelFormModel = new Whir.BLL.Whir_ModelForm();

        //字段标题数组
        string fieldTitles = "";

        //字段 ID 数组
        string fieldIDs = modelFormModel.GetFieldIDs(ModelFormID);
        strReturn[1] = fieldIDs;

        //字段列数组
        string fieldNames = "";

        string oldfieldNames = "";

        Whir.BLL.Whir_Field fieldBll = new Whir.BLL.Whir_Field();

        //获取标题列表
        DataTable dtTitles = fieldBll.GetList("FieldID in (" + fieldIDs + ") AND ModelID = " + ModelID).Tables[0];

        //获取字段列表
        DataTable dtContents = Whir.SQLServerDAL.DbHelperSQL.GetDataTable(" FieldName,FieldID ", "Whir_Field", " FieldID in (" + fieldIDs + ")", "Sort");

        //获取列标题
        foreach (DataRow dr in dtTitles.Rows)
        {
            fieldTitles += dr["alias"].ToString() + ",";
        }
        fieldTitles = fieldTitles.TrimEnd(',');
        strReturn[0] = fieldTitles;

        //获取表字段
        //Whir.BLL.Whir_Field fieldBll = new Whir.BLL.Whir_Field();
        Whir.Model.Whir_Field fieldModel = new Whir.Model.Whir_Field();
        string tempSTR = "";

        foreach (DataRow dr in dtContents.Rows)
        {
            oldfieldNames += dr["FieldName"].ToString().ToLower() + ",";

            fieldModel = fieldBll.GetModel(int.Parse(dr["FieldID"].ToString()));
            switch ((FieldType)fieldModel.fieldType)
            {
                case FieldType.ListBoxType://下拉类别
                    {
                        Whir.BLL.Whir_FieldOption OptionBll = new Whir.BLL.Whir_FieldOption();
                        int fieldTextId = int.Parse(OptionBll.GetList(" FieldID = " + fieldModel.fieldID).Tables[0].Rows[0][0].ToString());
                        Whir.Model.Whir_FieldOption optionModel = OptionBll.GetModel(fieldTextId);

                        if (optionModel.optionType != 3)//不是多选项
                        {
                            if (optionModel.bindType == 1)
                            {
                                tempSTR = dr["FieldName"].ToString().ToLower();
                            }
                            else if (optionModel.bindType == 2)
                            {
                                int index = optionModel.sql.ToLower().IndexOf("from");
                                string temp1 = optionModel.sql.Substring(index, optionModel.sql.Length - index);
                                if (temp1.ToLower().IndexOf("where") != -1)
                                {
                                    tempSTR = "( SELECT " + optionModel.textField + " " + temp1 + " AND " + optionModel.valueField + "=" + tableName + "." + dr["FieldName"].ToString() + ") as " + dr["FieldName"].ToString();
                                }
                                else
                                {
                                    tempSTR = "( SELECT " + optionModel.textField + " " + temp1 + " WHERE " + optionModel.valueField + "=" + tableName + "." + dr["FieldName"].ToString() + ") as " + dr["FieldName"].ToString();
                                }
                            }
                            else if (optionModel.bindType == 3)
                            {
                                //tempSTR = "(SELECT " + optionModel.textField + " FROM " + optionModel.sql + " WHERE " + optionModel.valueField + "=" + tableName + "." + dr["FieldName"].ToString() + ") as " + dr["FieldName"].ToString();
                                tempSTR = "(SELECT {1} FROM {0} a WHERE {2} = {3}.{4}) as {4}";
                                tempSTR = string.Format(tempSTR, optionModel.sql, optionModel.textField, optionModel.valueField, tableName, dr["FieldName"].ToString());
                            }
                            fieldNames += tempSTR.ToLower() + ",";
                        }
                        else
                        {
                            fieldNames += dr["FieldName"].ToString().ToLower() + ",";
                        }
                    }
                    break;
                case FieldType.PictureType:
                case FieldType.FileType:
                case FieldType.DateTimeType:
                case FieldType.BoolType:
                case FieldType.ColorType:
                case FieldType.LinkType:
                case FieldType.MoneyType:
                case FieldType.MultipleTextType:
                case FieldType.MultipleHtmlTextType:
                case FieldType.NumberType:
                case FieldType.TextType:
                    fieldNames += dr["FieldName"].ToString().ToLower() + ",";
                    break;
                default:
                    fieldNames += dr["FieldName"].ToString().ToLower() + ",";
                    break;
            }
        }
        fieldNames = fieldNames.TrimEnd(',');
        oldfieldNames = oldfieldNames.TrimEnd(',');

        strReturn[2] = fieldNames;
        strReturn[3] = oldfieldNames;

        return strReturn;
    }
    #endregion

    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        BindData();
    }

    #region 处理事件

    public void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //自定义的按钮事件
        if (CommonContentManage_RowCommand != null)
        {
            CommonContentManage_RowCommand(sender, e);
        }

        int rowID = Convert.ToInt32(e.CommandArgument);
        string itemID;
        string selectsql, updatesql, value;

        GridViewRow selectedRow = GridView1.Rows[rowID];
        itemID = GridView1.DataKeys[rowID].Value.ToString();
        selectsql = string.Format("SELECT {0} FROM {1} WHERE {2} = {3}", "{0}", tableName, primaryKeyName, itemID);
        updatesql = string.Format("UPDATE {0} SET {1} = '{2}' WHERE {3} = {4}", tableName, "{0}", "{1}", primaryKeyName, itemID);

        //处理事件
        switch (e.CommandName)
        {
            case "CheckItem":   //审核
                {
                    selectsql = string.Format(selectsql, "IsCheck");
                    value = Convert.ToString(Whir.SQLServerDAL.DbHelperSQL.GetSingle(selectsql));
                    value = value == "否" ? "是" : "否";
                    updatesql = string.Format(updatesql, "IsCheck", value);
                    Whir.SQLServerDAL.DbHelperSQL.ExecuteSql(updatesql);
                }
                BindData();
                break;
            case "TopItem":     //推荐
                {
                    selectsql = string.Format(selectsql, "IsTop");
                    value = Convert.ToString(Whir.SQLServerDAL.DbHelperSQL.GetSingle(selectsql));
                    value = value == "否" ? "是" : "否";
                    updatesql = string.Format(updatesql, "IsTop", value);
                    Whir.SQLServerDAL.DbHelperSQL.ExecuteSql(updatesql);
                }
                BindData();
                break;
            case "ModifyItem":  //编辑
                Response.Redirect("Content.aspx?ModelFormID=" + ModelFormID + "&ModelID=" + ModelID + "&Action=Modify&ItemID=" + itemID + "&TypeID=" + TypeID + "&url=" + Server.UrlEncode(NetRequest.GetUrl()));
                break;
            case "DeleteItem":  //删除                
                Response.Redirect("Content.aspx?ModelFormID=" + ModelFormID + "&ModelID=" + ModelID + "&Action=Delete&ItemID=" + itemID + "&TypeID=" + TypeID + "&url=" + Server.UrlEncode(NetRequest.GetUrl()));
                break;
            case "PreviewItem": //查看详细
                JsHelper.OpenWindow(Page, Whir.Common.Settings.GetString("SystemPath") + "html/" + TypeID + "/Info/" + itemID + ".html", "_blank");
                break;
        }
    }
    #endregion

    #region 批量删除到回收站
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        //获取被选中的编号
        int[] itemIds = this.GridView1.CheckedIndexs;
        if (itemIds.Length > 0)
        {
            string execsql = "";
            object obj;
            string file = "";
            foreach (int item in itemIds)
            {
                execsql = string.Format("DELETE FROM {0} WHERE {1} = {2}", tableName, primaryKeyName, item);

                Whir.SQLServerDAL.DbHelperSQL.ExecuteSql(execsql);

                obj = Whir.SQLServerDAL.DbHelperSQL.GetSingle(string.Format("SELECT Top 1 [CreateDate] From {0} WHERE {1} = {2}", tableName, primaryKeyName, item));
                if (obj != null)
                {
                    file = string.Format("~/html/{0}/{1}.html", ContentManage.GetDateTimeFormat(obj), TypeID + "_" + item);
                    file = Server.MapPath(file);
                    if (System.IO.File.Exists(file))
                    {
                        System.IO.File.Delete(file);
                    }
                }
            }
            JsHelper.Alert(Page, "该记录已删除成功！");

            //执行发布操作
            string[] msgstr = ContentManage.publish(TypeID, Page);
            bool flag = bool.Parse(msgstr[0]);
            if (!flag)
            {
                JsHelper.Alert(Page, "发布出错！" + msgstr[1]);
            }
        }
        else
        {
            JsHelper.Alert(Page, "请选择要删除的记录！");
            return;
        }
        BindData();
    }
    #endregion

    #region 截取字符串
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        int maxLength = 30;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            for (int i = 1; i < e.Row.Cells.Count - 2; i++)
            {
                string str = e.Row.Cells[i].Text;
                if (str.Length > maxLength)
                {
                    str = StringHelper.RemoveHtml(str);
                    str = Server.HtmlEncode(str);
                    str = StringHelper.CutString(str, 30);
                    e.Row.Cells[i].Text = str;
                }
            }
        }
    }
    #endregion

    #region 属性
    /// <summary>
    /// 功能模块ID
    /// </summary>
    public int ModelID
    {
        get
        {
            int _modelId = 0;
            if (this.ViewState["ModelID"] != null)
            {
                _modelId = Convert.ToInt32(ViewState["ModelID"].ToString());
            }
            return _modelId;
        }
        set { this.ViewState["ModelID"] = value; }
    }

    /// <summary>
    /// 功能模块表单ID
    /// </summary>  
    public int ModelFormID
    {
        get
        {
            int _modelFormId = 0;
            if (this.ViewState["ModelFormID"] != null)
            {
                _modelFormId = Convert.ToInt32(ViewState["ModelFormID"].ToString());
            }
            return _modelFormId;
        }
        set { this.ViewState["ModelFormID"] = value; }
    }

    /// <summary>
    /// 栏目ID
    /// </summary>
    public int TypeID
    {
        get
        {
            int _TypeID = 0;
            if (this.ViewState["TypeID"] != null)
            {
                _TypeID = Convert.ToInt32(ViewState["TypeID"].ToString());
            }
            return _TypeID;
        }
        set { this.ViewState["TypeID"] = value; }
    }

    /// <summary>
    /// 条件
    /// </summary>
    public string Where
    {
        get
        {
            string _where = "";
            if (this.ViewState["Where"] != null)
            {
                _where = ViewState["Where"].ToString();
            }
            return _where;
        }
        set { this.ViewState["Where"] = value; }
    }

    private string _settings;
    /// <summary>
    /// 事件操作添加
    /// Settings格式：有多个按钮，加“|”区分
    /// Settings 如果加事件：1,(show|hide),HeaderText,text,commandname
    /// Settings 如果加链接：2,(show|hide),HeaderText,text,NavigateUrl
    /// </summary>
    public string Settings
    {
        get
        {
            if (ViewState["Settings"] != null)
            {
                _settings = ViewState["Settings"].ToString();

                //验证"Settings"的格式是否正确
                if (_settings != "")
                {
                    string[] temp = _settings.Split('|');
                    for (int i = 0; i < temp.Length; i++)
                    {
                        if (temp[i].Split(',').Length != 5)
                        {
                            throw new ArgumentException("参数格式不正确");
                        }
                    }
                }
            }
            return _settings;
        }
        set { ViewState["Settings"] = value; }
    }
    #endregion

    #region IContentUserControl 成员

    //搜索时，设置条件
    public void setValue(string where)
    {
        Where = where;
    }

    #endregion

    #region 将回收站中的数据恢复
    protected void btnRe_Click(object sender, EventArgs e)
    {
        //获取被选中的编号
        int[] itemIds = this.GridView1.CheckedIndexs;
        if (itemIds.Length > 0)
        {
            string updatesql = "";
            foreach (int item in itemIds)
            {
                updatesql = string.Format("UPDATE {0} SET [IsRecycle] = 0 WHERE {1} = {2}", tableName, primaryKeyName, item);
                Whir.SQLServerDAL.DbHelperSQL.ExecuteSql(updatesql);
            }
            JsHelper.Alert(Page, "该记录已成功恢复，请重新发布此栏目！");
        }
        else
        {
            JsHelper.Alert(Page, "请选择要恢复的记录！");
        }
        BindData();
    }
    #endregion
}
